<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Http\Models\Config;

class ConfigController extends Controller {


    public function index(Request $request)
    {
        //data不可数
        $data = Config::orderBy("created_at","asc");
        $data = $data->paginate(20);


        return view("admin.config.index",['data'=>$data,'active'=>'system']);
    }

    public function create(Request $request)
    {

        return view('admin.config.create',['active'=>'system']);
    }

    public function store(Request $request){
        $ckey =  $request -> input('ckey');
        $hasConfig = Config::where('ckey',$ckey)->first();
        if($hasConfig){
            $config = Config::find($hasConfig['id']);
            $config -> title = $request->input('title');
            $config -> cval = $request -> input('cval');
        }else {
            $config = new Config;
            $config->title = $request->input('title');
            $config->ckey = $request->input('ckey');
            $config->cval = $request->input('cval');
        }
        $config->save();
        if($request->ajax()){
            return response()->json(['state'=>'ok','message'=>'保存成功']);
        }
        return redirect('/admin/config');
    }

    public function edit($id)
    {

        $config = Config::find($id);

        return view('admin.config.edit',['config'=>$config]);
    }


    public function update(Request $request,$id)
    {
        $config = Config::find($id);

        $config ->title = $request -> input('title');
        $config ->ckey = $request -> input('ckey');
        $config ->cval = $request -> input('cval');

        $config->save();

        return redirect('/admin/config');
    }

    public function delete($id)
    {
        $res = Config::destroy($id);
        if($res) return view('success',['url'=>'/admin/config']);

        return view('failure',['url'=>'/admin/config']);
    }


}
